<template>
  <div>
    <h2>{{ editing ? 'Edit User' : 'Add User' }}</h2>
    <form @submit.prevent="submitForm">
      <label for="username">Username:</label>
      <input id="username" v-model="form.username" required>

      <label for="email">Email:</label>
      <input type="email" id="email" v-model="form.email" required>

      <button type="submit">Submit</button>
    </form>
  </div>
</template>

<script>
export default {
  props: {
    initialData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        id: this.initialData.id || '',
        username: this.initialData.username || '',
        email: this.initialData.email || ''
      },
      editing: !!this.initialData.id
    };
  },
  methods: {
    submitForm() {
      const action = this.editing ? 'updateUser' : 'createUser';
      this.$emit(action, this.form);
      this.resetForm();
    },
    resetForm() {
      this.form = { id: '', username: '', email: '' };
      this.editing = false;
    }
  },
  watch: {
    initialData(newVal) {
      this.form.id = newVal.id || '';
      this.form.username = newVal.username || '';
      this.form.email = newVal.email || '';
      this.editing = !!newVal.id;
    }
  }
};
</script>
